package com.hjm.common.api.ls.leshua.ls;

import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.Base64;

public class ImageUtil {
    // 将BufferedImage编码为Base64字符串
    public static String encodeImageToBase64(String imagePath) throws IOException {
        BufferedImage image = ImageIO.read(new File(imagePath));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", baos);
        byte[] imageBytes = baos.toByteArray();
        return Base64.getEncoder().encodeToString(imageBytes);
    }

    // 将BufferedImage编码为Base64字符串
    public static String encodeImageToBase64(File imagePath) throws IOException {
        BufferedImage image = ImageIO.read(imagePath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        String fileName=imagePath.getName();
        fileName=fileName.substring(fileName.indexOf(".")+1,fileName.length());

        System.out.println("aaaa"+fileName);

        ImageIO.write(image, "jpg", baos);
        byte[] imageBytes = baos.toByteArray();
        return Base64.getEncoder().encodeToString(imageBytes);
    }

    // 将Base64字符串解码为BufferedImage
    public static BufferedImage decodeBase64ToImage(String base64ImageString) throws IOException {
        byte[] imageBytes = Base64.getDecoder().decode(base64ImageString);
        return ImageIO.read(new ByteArrayInputStream(imageBytes));
    }

    public static File downloadWxImage(String url) {
        File file = null;
        URL urlfile;
        InputStream inputStream = null;
        OutputStream outputStream= null;
        try {
            String fileName=url.substring(url.lastIndexOf("."),url.length());
            file = File.createTempFile("wx_image", fileName);
            //下载
            urlfile = new URL(url);
            inputStream = urlfile.openStream();
            outputStream= new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    public static String fileToBase64Str(File file) throws IOException {
        String base64Str = null;
        FileInputStream fin = null;
        BufferedInputStream bin = null;
        ByteArrayOutputStream baos = null;
        BufferedOutputStream bout = null;
        try {
            fin = new FileInputStream(file);
            bin = new BufferedInputStream(fin);
            baos = new ByteArrayOutputStream();
            bout = new BufferedOutputStream(baos);
            // io
            byte[] buffer = new byte[1024];
            int len = bin.read(buffer);
            while(len != -1){
                bout.write(buffer, 0, len);
                len = bin.read(buffer);
            }
            // 刷新此输出流，强制写出所有缓冲的输出字节
            bout.flush();
            byte[] bytes = baos.toByteArray();
            // Base64字符编码
            base64Str = Base64.getEncoder().encodeToString(bytes).trim();
        } catch (IOException e) {
            e.getMessage();
        } finally{
            try {
                fin.close();
                bin.close();
                bout.close();
            } catch (IOException e) {
                e.getMessage();
            }
        }
        return resizeImageTo40K(base64Str);
    }

    public static String resizeImageTo40K(String base64Img) {
        try{
            byte[] bytes1 = Base64.getDecoder().decode(base64Img);
            InputStream   stream = new ByteArrayInputStream(bytes1);
            BufferedImage src = ImageIO.read(stream);
            BufferedImage output = Thumbnails.of(src).size(src.getWidth() / 3, src.getHeight() / 3).asBufferedImage();
            String base64 = imageToBase64(output);
            if (base64.length() - base64.length() / 8 * 2 > 80000) {
                output = Thumbnails.of(output).scale(1 / (base64.length() / 80000)).asBufferedImage();
                base64 = imageToBase64(output);
            }
            return base64;
        } catch (Exception e) {
            return base64Img;
        }
    }

    public static String imageToBase64(BufferedImage bufferedImage) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, "jpg", baos);
        } catch (IOException e) {
        }
        return new String(Base64.getEncoder().encode((baos.toByteArray())));
    }
}
